#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理
#include <QDebug>


void MainWindow::handleCommand304(const QMap<QString, QString>& params, QTcpSocket* client)
{
    // 1. 参数校验
    if (!params.contains("CamID") || !params.contains("FITS_Header") || !params.contains("FITS_Name")) {
        sendResponse("<ID=304><INFO=Error><MSG=Missing_parameters>", client);
        return;
    }

    QString camId = params["CamID"];
    QString fitsHeader = params["FITS_Header"];
    QString fitsName = params["FITS_Name"];

    // 2. 立即返回确认响应
    sendResponse("<ID=304><INFO=OK>", client);

    // 3. 在后台线程中处理FITS文件和计算中值
    QtConcurrent::run([this, camId, fitsHeader, fitsName, client]() {
        // 解析JSON头信息
        QJsonParseError jsonError;
        QJsonDocument doc = QJsonDocument::fromJson(fitsHeader.toUtf8(), &jsonError);
        if (doc.isNull()) {
            QString errorResponse = QString("<ID=304><CamID=%1><INFO=Error><MSG=Invalid_JSON_format><SENDTIME=%2>;")
            .arg(camId)
                .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
            sendResponse(errorResponse, client);
            return;
        }

        QJsonObject headerObj = doc.object();

        // 构建完整文件路径
        QString fitsFilePath = QDir(fitsSavePath).absoluteFilePath(fitsName);
        if (!fitsFilePath.endsWith(".fits")) {
            fitsFilePath += ".fits";
        }

        // 检查文件是否存在
        if (!QFile::exists(fitsFilePath)) {
            QString errorResponse = QString("<ID=304><CamID=%1><INFO=Error><MSG=File_not_found><SENDTIME=%2>;")
            .arg(camId)
                .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
            sendResponse(errorResponse, client);
            return;
        }

        // 计算图像中值（仅对平场类型）
        double fitsMedian = -999.0; // 默认非平场值
        if (headerObj.contains("IMAGETYP")) {
            QString imageType = headerObj["IMAGETYP"].toString().toLower();
            if (imageType == "flat" || imageType == "df" || imageType == "ff") { // 平场类型
                try {
                    fitsMedian = calculateFitsMedian(fitsFilePath);
                    /*LOG_GENERAL(QString("计算平场中值完成 [Cam:%1][File:%2][Median:%3]")
                                 .arg(camId)
                                 .arg(QFileInfo(fitsFilePath).fileName())
                                 .arg(fitsMedian));*/
                    threadSafeLog("INFO", QString("计算平场中值完成 [Cam:%1][Median:%2]")
                                              .arg(camId).arg(fitsMedian));
                } catch (const std::exception& e) {
                    LOG_GENERAL(QString("calculateFitsMedian failed: %1").arg(e.what()));
                }
            }
        }

        // 更新FITS头信息
        bool headerUpdated = updateFitsHeader(fitsFilePath, headerObj);

        // 构造最终响应
        QString response = QString("<ID=304><CamID=%1><INFO=%2><ACTION=DONE><Fits_Median=%3><SENDTIME=%4>;")
                               .arg(camId)
                               .arg(headerUpdated ? "OK" : "Error")
                               .arg(fitsMedian, 0, 'f', 2)
                               .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));

        // 在主线程发送响应
        QMetaObject::invokeMethod(this, [this, client, response]() {
            sendResponse(response, client);
        });
    });
}